package logic.ships.autoWeaponShip;

import logic.NodeController;
import logic.nodes.TeamNode;
import logic.ships.moveableShip.MovableShip;
import logic.weapons.Weapon;
import logic.weapons.WeaponFire;
import logic.weapons.energyWeapons.EnergyWeapon;
import logic.weapons.projectileWeapons.missile.MissileWeapon;

import ai.AITools;

import com.jme.math.Vector3f;

public class AutoWeaponController extends NodeController {
	
	private static final long serialVersionUID = 1L;
	
	protected Weapon weapon;
	protected AutoWeaponShip ship;
	protected float targetTime, weaponRange;
	protected TeamNode target;
	protected BlockFinder blockFinder;
	protected boolean isVisible;
	
	public AutoWeaponController(Weapon weapon, AutoWeaponShip ship, BlockFinder blockFinder) {
		super(0f, weapon);
		this.weapon = weapon;
		this.ship = ship;
		this.blockFinder = blockFinder;
		
		weaponRange = ship.getFireRangeOf(weapon);
	}
	
	@Override
	public void extraUpdate(float time) {
		if(target == null || target.isDestroyed() || (weapon instanceof MissileWeapon 
		&& target instanceof MovableShip && ((MovableShip)target).getCurrentEngineSpeed() > 0.05f)) return;
		
		Vector3f weaponLoc = weapon.getFireSpotLocation();
		Vector3f targetLoc = target.getLocalTranslation();
		float dist = targetLoc.distance(weaponLoc);
		
		float rotateSpeed = time;
		
		if(dist <= weaponRange && isVisible) {
			Vector3f direction = targetLoc.subtract(weaponLoc).normalize();
			if(weapon instanceof EnergyWeapon) {
				Vector3f aimLoc = AITools.getEnergyFireLocation((EnergyWeapon)weapon, target);
				direction = aimLoc.subtract(weapon.getFireSpotLocation());
			}
			WeaponFire fire = weapon.fire(direction);
			if(fire != null) weapon.getIngameState().addNode(fire);
			
			rotateTo(targetLoc, rotateSpeed, false);
		}
	}
	
	public void setTarget(TeamNode target, boolean isVisible) {
		this.target = target;
		this.isVisible = isVisible;
	}
	
	@Override
	protected void delayedUpdate(float time) {}
}